package com.water.expert.extraction.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.water.expert.extraction.repository.Profession;
import com.water.expert.extraction.repository.ProfessionRepository;

import jakarta.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/professions")
public class ProfessionController {
    @Autowired
    private ProfessionRepository professionRepository;

    // 获取所有项目
    @GetMapping
    public List<Profession> getAllProfessions(HttpServletRequest req) {
        return professionRepository.findAll();
    }

    // 根据 ID 获取项目
    @GetMapping("/{id}")
    public ResponseEntity<Profession> getProfessionById(@PathVariable Long id) {
        return professionRepository.findById(id)
                .map(ResponseEntity::ok)
                .orElseGet(() -> ResponseEntity.notFound().build());
    }

    // 创建项目
    @PostMapping
    public Profession createProfession(@RequestBody Profession Profession) {
        return professionRepository.save(Profession);
    }

    // 更新项目
    @PutMapping("/{id}")
    public ResponseEntity<Profession> updateProfession(@PathVariable Long id, @RequestBody Profession updatedProfession) {
        return professionRepository.findById(id)
                .map(Profession -> {
                    updatedProfession.setId(id);
                    return ResponseEntity.ok(professionRepository.save(updatedProfession));
                })
                .orElseGet(() -> ResponseEntity.notFound().build());
    }

    // 删除项目
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteProfession(@PathVariable Long id) {
        return professionRepository.findById(id)
                .map(Profession -> {
                    professionRepository.deleteById(id);
                    return ResponseEntity.ok().<Void>build();
                })
                .orElseGet(() -> ResponseEntity.notFound().build());
    }
}
